<template>
    <div>
        <div class="search-form">
            <el-form :model="searchForm" :rules="rules" inline>
                <el-form-item label="课程ID">
                    <el-input v-model="searchForm.courseID" @keyup.enter="search" placeholder="请输入课程ID"></el-input>
                </el-form-item>
                <el-form-item label="课程姓名">
                    <el-input v-model="searchForm.courseName" @keyup.enter="search" placeholder="请输入课程姓名"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search">搜索</el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="inputDiv">
            <el-form-item label="课程名称">
                <el-input v-model="addForm.courseName" />
            </el-form-item>
            <el-form-item label="课程限制信息">
                <el-input v-model="addForm.sysRole" />
            </el-form-item>
            <el-button class="import-el-button" @click="addPerson()">添加</el-button>
        </div>
        <el-dialog title="添加课程章节信息" v-model="dialogChapterVisible" :before-close="handleClose">
            <el-button @click="addItemForChapter">添加章节</el-button>
            <el-form :model="chapterItem">
                <el-form-item v-for="(item, index) in chapterItem" :key="index" :label="`第${index + 1}章`"
                    :label-width="formLabelWidth">
                    <el-input v-model="chapterItem[index]" autocomplete="off" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer" @click="dialogChapterVisible = false">
                    <el-button>取消</el-button>
                    <el-button type="primary" @click="saveChapter()">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
        <el-button class="import-el-button" @click="downLoadStu()">下载名单</el-button>
        <el-table ref="multipleTableRef" :data="displayedCourse" style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column property="courseName" label="courseName" />
            <el-table-column property="courseID" label="courseID" show-overflow-tooltip />
            <el-table-column label="操作" width="360">
                <template #default="{ row }">
                    <el-button link type="primary" size="small" @click="editPerson(row)">编辑</el-button>
                    <el-dialog title="编辑课程信息" v-model="dialogFormVisible" :before-close="handleClose">
                        <el-form :model="form">
                            <el-form-item label="课程名称" :label-width="formLabelWidth">
                                <el-input v-model="form.courseName" autocomplete="off" />
                            </el-form-item>
                            <el-form-item label="课程ID" :label-width="formLabelWidth">
                                <el-input v-model="form.courseID" autocomplete="off" />
                            </el-form-item>
                            <el-form-item label="课程限制信息" :label-width="formLabelWidth">
                                <el-input v-model="form.sysRole" autocomplete="off" />
                            </el-form-item>
                        </el-form>
                        <template #footer>
                            <span class="dialog-footer" @click="dialogFormVisible = false">
                                <el-button>取消</el-button>
                                <el-button type="primary" @click="saveEdit(row)">
                                    確定
                                </el-button>
                            </span>
                        </template>
                    </el-dialog>
                    <el-button link type="primary" size="small" @click="deleteSingleTeacherFun(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[5, 10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="course.length">
        </el-pagination>
        <div style="margin-top: 20px">
            <el-button @click="deleteBatchTeacher">批量删除</el-button>
        </div>
    </div>
</template>
  
<script setup>
import { ref, toRefs, reactive, computed, watch, onMounted } from 'vue';
import { ElNotification, ElDialog, ElForm, ElFormItem, ElInput, ElButton, ElPagination, ElMessage } from 'element-plus';
import XLSX from 'xlsx';
import { useStore } from '../store'
import { ElTable, ElUpload } from 'element-plus'
import { addSingleCourse, deleteSingleCourse, editorCourseInfo, deleteBatchCourses, selectCourse, addChapter } from '@/api/adminApi/allAdmin'
const store = useStore()
const fileList = ref()
const dialogChapterVisible = ref(false)
watch(
    () => store.courseList,
    () => course.value = store.courseList,
    { deep: true }
)
const course = ref(store.courseList);
const form = ref({
    courseID: '',
    courseName: '',
    editIndex: 0,
    sysRole: ''
});
const addForm = ref({
    courseName: '',
    courseID: '',
    sysRole: ''
});
const displayedCourse = ref([]); // 当前显示的数据
const currentPage = ref(1);
const pageSize = ref(10);

const handleSizeChange = (val) => {
    pageSize.value = val;
    currentPage.value = 1;
    displayedCourse.value = paginateData();
};

const handleCurrentChange = (val) => {
    currentPage.value = val;
    displayedCourse.value = paginateData();
};

const paginateData = () => {
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const endIndex = startIndex + pageSize.value;
    return course.value.slice(startIndex, endIndex);
};
onMounted(() => {
    displayedCourse.value = paginateData();
})
const multipleTableRef = ref()
const dialogFormVisible = ref(false);
const addPerson = async () => {
    const data = {
        courseName: addForm.value.courseName,
        sysRole: addForm.value.sysRole
    };
    course.value.push(data)
    let res = await addSingleCourse(data)
    if (res.code !== 300) {
        ElMessage.error(res.msg)
    }
    else {
        dialogChapterVisible.value = true
        lastAddCourse.value = addForm.value.courseName
    }
    addForm.value = {}
};
const chapterItem = ref([])
const lastAddCourse = ref('')
const addItemForChapter = () => {
    chapterItem.value.push('')
}
const saveChapter = async () => {
    let data = chapterItem.value.map((chapter, index) => {
        return {
            chapterNum: index + 1,
            chapterName: chapter.charAt(0).toUpperCase() + chapter.slice(1).replace(/([A-Z])/g, ' $1').trim()
        };
    });
    let params={
        courseName:lastAddCourse.value
    }
    await addChapter(params, data)
}
//保存多选行的信息
const selectionRow = ref([])
const handleSelectionChange = (section) => {
    selectionRow.value = section
    console.log(selectionRow.value, 'selectionRow')
}
//批量删除
const deleteBatchTeacher = async () => {
    const data = []
    selectionRow.value.map((item, index) => {
        data.push(item.courseID)
        course.value.map((list, idx) => {
            if (item.courseID === list.courseID)
                displayedCourse.value.splice(idx, 1)
        })
    })
    await deleteBatchCourses(data)
}
const editPerson = async (row) => {
    // 处理选中行数据
    form.value.courseName = row.courseName;
    form.value.courseID = row.courseID;
    form.value.sysRole = row.sysRole;
    dialogFormVisible.value = true;
}
//删除单个课程
const deleteSingleTeacherFun = async (row) => {
    const index = course.value.findIndex(item => item.courseID === row.courseID);
    console.log(index, 'index')
    displayedCourse.value.splice(index, 1)
    await deleteSingleCourse(row.courseID)
    ElMessage.success('正在删除，刷新页面更新数据')
};
//保存内容
const saveEdit = async () => {
    const data = {
        courseName: form.value.courseName,
        courseID: form.value.courseID,
        sysRole: form.value.sysRole
    }
    await editorCourseInfo(data)
    const index = course.value.findIndex((item) => item.courseID === form.value.courseID)
    displayedCourse.value[index].courseName = form.value.courseName
}
const searchForm = ref({
    courseID: '',
    courseName: ''
})
const resetForm = () => {
    searchForm.value.classID = '';
    searchForm.value.className = '';
};
const search = async () => {
    let result = {
        courseID: searchForm.value.courseID,
        courseName: searchForm.value.courseName,
        pageSize: 20,
        pageNum: 1
    }
    const res = await selectCourse(result)
    displayedCourse.value = res.data

};
const handleCloseDialog = (done) => {
    form.value.courseID = '';
    form.value.teachercourseName = '';
    done();
};

// 将响应式数据转换为可解构的对象
const { value: reactivecourse } = toRefs(course);
const downLoadStu = () => {
    const worksheet = XLSX.utils.json_to_sheet(course.value);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    XLSX.writeFile(workbook, 'courses.xlsx');
}
const handleFileUpload = (event) => {
    const file = event.target.files[0];
    const reader = new FileReader();

    reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const worksheet = workbook.Sheets[workbook.SheetcourseNames[0]];
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

        // 将数据存入ref
        course.value = jsonData.map((row, index) => {
            if (index === 0) return null; // 跳过表头行
            const [id, courseID, courseName] = row;
            return { id, courseID, courseName };
        }).filter(Boolean);
    };

    reader.readAsArrayBuffer(file);
}

</script>
  
<style>
.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

.import_div {
    display: inline-block;
    margin-left: 28%;
}
</style>
  
  <!-- 引入 Element Plus 组件库 -->
<script>
export default {
    components: {
        ElNotification,
        ElDialog,
        ElForm,
        ElFormItem,
        ElInput,
        ElButton,
    },
};
</script>@/api/adminApi/allAdmin